package com.bw.aop;

import cn.hutool.http.server.HttpServerRequest;
import com.bw.domain.SysUser;
import com.bw.service.SysUserService;
import com.bw.utils.common.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author bobo棒
 * @date 2024年03月07日 15:34
 */
@Slf4j
@Aspect //标记当前类是切面类
@Component //被spring容器管理
public class LogAop {
    @Autowired
    HttpServletRequest request;
    @Autowired
    SysUserService sysUserService;
    //环绕通知
    //切点表达式: 拦截controller下所有类所有方法
     @Around(value = "execution(* com.bw.controller.*.*(..) )")
    public  Object log(ProceedingJoinPoint pjp) throws Throwable {
      //ip地址、用户名、请求的地址，请求的时间
         String ip = request.getRemoteAddr();
         String userId = JWTUtils.getUserId();
         String username="未登录用户";
         if(null!=userId){//登录用户
             SysUser user = sysUserService.getById(userId);
             username =user.getUsername();
         }
         String url =request.getRequestURI();//请求的地址
         Date time =new Date();
         log.info("ip:{},用户名:{},请求的地址:{},请求的时间:{}",ip,username,url,time);
        //放行
         Object proceed = pjp.proceed();//放行
         return  proceed;

     }
}
